package com.mgface.zookeeper.curator.function;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.barriers.DistributedDoubleBarrier;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class 分布式Barrier线程自动触发 {

	public static void main(String[] args) throws InterruptedException {
		String path = "/curator-barrier/auto2";
		ExecutorService exec = Executors.newFixedThreadPool(4);
		for (int i = 0; i < 4; i++) {
			exec.submit(()->{
				CuratorFramework client = CuratorFrameworkFactory.builder().connectString("localhost:2181,localhost:2182,localhost:2183")
						.connectionTimeoutMs(20_000).sessionTimeoutMs(20_000)
				.retryPolicy(new ExponentialBackoffRetry(1_000, 3)).build();
				client.start();
				//控制同时进入和退出
				DistributedDoubleBarrier db = new DistributedDoubleBarrier(client, path,4);
				try {
					System.out.println("当前:"+Thread.currentThread().getName()+"号barrier设置");
					db.enter();//进行等待，准备进入状态
					System.out.println("启动...");
					TimeUnit.SECONDS.sleep(1);
					db.leave();//再次等待，准备退出状态
					System.out.println("退出...");
				} catch (Exception e) {
					e.printStackTrace();
				}
			});
		}
		exec.shutdown();
		exec.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS);
		System.out.println("执行完毕...");
	}

}
